# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

"""
case Table  景区表
add 
delete
modify
...
"""


import time
import utils.pgsql.base.pgconn as pgconn
import json
import utils.common.log as log


_tblName = "tbl_case"

_DB_SCRIPT = """
CREATE TABLE IF NOT EXISTS {} (
                "caseId"  SERIAL PRIMARY KEY ,   -- 景区id
                "operatorId" INTEGER NOT NULL default 0,   -- 渠道id   
                "adminId" INTEGER NOT NULL default 0,   -- 登录账户id   
                "ticketPrice" INTEGER NOT NULL default 0,     
                "caseName"  VARCHAR(260) NOT NULL default '' unique,  -- 景区名称 
                "type" VARCHAR(64) NOT NULL default '1',   -- 景区类型，1：景点  热门景区 趣味乐园 数智乡村 自定义
                "address" VARCHAR(260) NOT NULL default '',   -- 景区地址 
                "description" VARCHAR(260) NOT NULL default '', -- 景区描述   
                "descriptionMore" JSON,    
                "coverImgUrl" VARCHAR(260)   NOT NULL default '',    
                "coverImgUrlScale" VARCHAR(260)   NOT NULL default '',    
                "playWayImgUrl" VARCHAR(260)   NOT NULL default '',   -- 玩法图片 
                "appletImgUrl" VARCHAR(260)   NOT NULL default '',  -- 小程序图
                "propagateVideoUrl" VARCHAR(260)   NOT NULL default '',    -- 宣传视频
                "states" VARCHAR(260) NOT NULL default '1', -- 景区状态 1：已生效，2：正在审批，3：已失效，4：已驳回 （上线下线）
                "location" JSON,  -- 经纬度
                "orCode"  VARCHAR(260) NOT NULL default '',    
                "equipmentFor" JSON, --设备申请信息
                "caseNameshort" VARCHAR(260)   NOT NULL default '无',   
                "auditstatus" VARCHAR(32)   NOT NULL default '未审核', 
                "createTime" VARCHAR(32) NOT NULL default '',
                "updateTime" VARCHAR(32) NOT NULL default '',
                "AIfacilitator" VARCHAR(32) NOT NULL default '', --算法中心
                "AIUrl" VARCHAR(512) NOT NULL default '', --算法中心链接
                "dataValid" INTEGER NOT NULL default 1  -- 逻辑删除
                );

""".format(
    _tblName
)

playground = """
CREATE TABLE playground(
   "id"       SERIAL PRIMARY KEY,
   "case_id"       integer REFERENCES tbl_case ("caseId"),
   "name"  VARCHAR(128) NOT NULL default '' ,  -- 游玩项目名称 
   "ai_ip"  CHAR (64)  NOT NULL,
   "states" VARCHAR(260) NOT NULL default '1', -- 游玩项目状态 1：已生效，2：正在审批，3：已失效，4：已驳回 （上线下线）
   "createTime" VARCHAR(32) NOT NULL default '',
   "updateTime" VARCHAR(32) NOT NULL default '',
   "dataValid" INTEGER NOT NULL default 1  -- 逻辑删除
);
"""

class PgCase:
    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create 
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

     
    def add(self, dic) -> str:
        if "createTime" not in dic:
            dic["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if "location" in dic:
            dic["location"] = json.dumps(dic["location"])
        if "descriptionMore" in dic:
            dic["descriptionMore"] = json.dumps(dic["descriptionMore"])
        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'
      
        sql = f"""insert into {_tblName} ({sql_key}) values ({sql_val[:-1]}) RETURNING "{"caseId"}" """
        return pgconn.pgMainConn.exec_fetchone(sql)

      
    def update_adminId(self, caseId, adminId) -> list:
        sql = f"""update {_tblName} set "adminId" = '{adminId}' where "caseId" = '{caseId}' """
        return pgconn.pgMainConn.exec(sql)

    def city_add_case(self,case_list,grant_date,adminId):
        sql = f"""insert into city ("caseName","grantDate","account_id") VALUES ('{case_list}','{grant_date}',{adminId})"""
        return pgconn.pgMainConn.exec(sql)

    def modify(self, dic, keys, ids) -> bool:
        '''modify'''
        dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if "location" in dic:
            dic["location"] = json.dumps(dic["location"])
        if "descriptionMore" in dic:
            dic["descriptionMore"] = json.dumps(dic["descriptionMore"])
        if "equipmentFor" in dic:
            dic["equipmentFor"] = json.dumps(dic["equipmentFor"])
        sql_key = ''
        for key in dic:
            if key =="AIUrl":
                dic["AIUrl"]= ",".join(dic["AIUrl"])
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'

        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1]) + " \"{}\" = '{}' ".format(keys, ids)
        return self._pgConn.exec(sql)

    
    def updateState(self, states, caseId) -> bool:
        sql = f"""update {_tblName} set "states" = '{states}' where "caseId" = '{caseId}' """
        print(sql)
        return self._pgConn.exec(sql)

    def update_auditstatus_State(self, auditstatus,states, caseId) -> bool:
        sql = f"""update {_tblName} set "states" = '{states}',"auditstatus" = '{auditstatus}' where "caseId" = '{caseId}' """
        print(sql)
        return self._pgConn.exec(sql)

     
    def get(self, ids) -> dict:
        sql = f"""select * from {_tblName} where "caseId" = '{ids}' and "dataValid" = '1' """
        return self._pgConn.exec_fetchone(sql)

      
    def get_caseName(self, caseId) -> dict:
        sql = 'select "caseName" from {} where "caseId" = \'{}\' and "dataValid" = \'1\' '.format(
            _tblName, caseId
        )
        return self._pgConn.exec_fetchone(sql)

     
    def get_caseName(self, caseId) -> dict:
        sql = 'select "caseName" from {} where "caseId" = \'{}\' and "dataValid" = \'1\' '.format(
            _tblName, caseId
        )
        return self._pgConn.exec_fetchone(sql)

      
    def get_auditatatus(self) -> dict:
        sql = "select * from {} where \"auditatatus\" = '审核中' and \"dataValid\" = '1' ".format(
            _tblName
        )
        return self._pgConn.exec_fetchall(sql)

      
    def allByOperator(self, tenantId) -> list:
        sql = 'select a.*,n."operatorName" from {} a left Join tbl_operator n on {}=n."operatorId"  where a."operatorId" = \'{}\' and a."dataValid" = \'1\' and  n."dataValid" = \'1\' order by a."caseId" '.format(
            _tblName, tenantId, tenantId
        )
        # sql = f"""select * from {_tblName} where "operatorId" = '{tenantId}'"""
        return self._pgConn.exec_fetchall(sql)

      
    def putCase(self, userInfo) -> dict:
        userInfo["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = ''
        for key in userInfo:
            if type(userInfo[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + userInfo[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(userInfo[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])  + " \"caseId\" = '{}' ".format(
            userInfo["caseId"]
        )
        return self._pgConn.exec(sql)

      
    def getBycaseId(self, caseId) -> dict:
        sql = f'select a.*,n."operatorName" from {_tblName} a left Join tbl_operator n on a."operatorId"=n."operatorId" where a."caseId" = \'{caseId}\' and  n."dataValid" = \'1\'  order by a."caseId" '
        tmp = self._pgConn.exec_fetchall(sql)
        plays = self.get_playground()
        for i in tmp:
            i['plays'] = []
            if 'bjy' in i['AIfacilitator']:
                for j in plays:
                    if j['case_id'] == i['caseId']:
                        i['plays'].append(j)
        return tmp
        # return self._pgConn.exec_fetchall(sql)

    def tech_all(self) -> list:
        sql = 'select a.*,n."operatorName" from {} a left Join tbl_operator n on a."operatorId"=n."operatorId" where a."dataValid" = \'1\' and  n."dataValid" = \'1\' order by a."caseId" '.format(
            _tblName
        )
        sql = """
        select a.*,n."operatorName",COUNT(b."AIstates") AS device_sum 
        from tbl_case a left Join tbl_operator n 
        on a."operatorId"=n."operatorId" LEFT JOIN tbl_device b ON b."caseId"=a."caseId" AND b."AIstates"='1' 
        where a."dataValid" = '1' and  n."dataValid" = '1' and a."states"='1'
        GROUP BY a."caseId" ,n."operatorName"
        """
        # 对bjy特殊处理，如果景区没有设备在线就把景区改成下线状态
        tmp = self._pgConn.exec_fetchall(sql)
        for i in tmp:
            if i['AIfacilitator'] == 'bjy' and i['device_sum']==0:
                i['notice'] = '下线' # '1'在线 '3'下线
            else:
                i['notice'] = '在线'
        return tmp

    def all(self) -> list:
        # bg_sql = """SELECT a.*,count(b."deviceName") AS device_sum from tbl_device b  LEFT JOIN tbl_case a
        # ON b."caseId"=a."caseId" GROUP BY a."caseId" ORDER BY "device_sum" desc"""

        bg_sql = """SELECT a.*,count(b."deviceName") AS device_sum from tbl_device b  LEFT JOIN tbl_case a 
        ON b."caseId"=a."caseId" where b."auditstatus" ='审核成功' GROUP BY a."caseId" ORDER BY "device_sum" desc;"""

        sql = """
        select a.*,n."operatorName",COUNT(b."AIstates") AS device_sum 
        from tbl_case a left Join tbl_operator n 
        on a."operatorId"=n."operatorId" LEFT JOIN tbl_device b ON b."caseId"=a."caseId" AND b."AIstates"='1' 
        where a."dataValid" = '1' and  n."dataValid" = '1' 
        GROUP BY a."caseId" ,n."operatorName" ORDER BY "device_sum" DESC
        """
        boguan_data = pgconn.boguan_db.exec_fetchall(bg_sql)
        # 对bjy特殊处理，如果景区没有设备在线就把景区改成下线状态
        tmp = self._pgConn.exec_fetchall(sql)
        plays = self.get_playground()
        for i in tmp:
            if i['AIfacilitator'] == 'bjy' and i['device_sum']==0:
                i['notice'] = '下线' # '1'在线 '3'下线
            else:
                i['notice'] = '在线'
            i['plays'] = []
            if 'bjy' in i['AIfacilitator']:
                for j in plays:
                    if j['case_id'] == i['caseId']:
                        i['plays'].append(j)
            if 'bg' in i['AIfacilitator']:
                for k in boguan_data:
                    if k['caseId'] ==i['caseId']:
                        i['device_sum'] += k['device_sum']
        def oreder(a):
            return a['device_sum']
        ordered_list = sorted(tmp, key=oreder, reverse=True)
        return ordered_list

    def allget(self) -> list:
        sql = 'select a.*,n."operatorName" from {} a left Join tbl_operator n on a."operatorId"=n."operatorId"  order by a."caseId" '.format(
            _tblName
        )
        return self._pgConn.exec_fetchall(sql)

      
    def soft_delete(self, ids, caseName) -> bool:
        # 逻辑删除状态置为 0
        caseName = caseName + str(int(time.time()))
        sql = 'update {} set "dataValid" = 0  ,"caseName" = \'{}\' where "caseId" = \'{}\''.format(
            _tblName, caseName, ids
        )
        return self._pgConn.exec(sql)

    def soft_delete_byop(self, operatorId) -> bool:
        sql = 'update {} set "dataValid" = 0 where "operatorId" =  \'{}\' '.format(
            _tblName, operatorId
        )
        return self._pgConn.exec(sql)
    
    def delete(self, ids) -> bool:
        sql = "delete from {} where \"caseId\" = '{}' ".format(_tblName, ids)
        return self._pgConn.exec(sql)


    def case_AIstates_sql(self) -> list:
        """
        算法接口 查询景区审核状态 AIstates
        :return: 
        """
        sql = 'select "caseId","AIstates" as "states" from {} where "dataValid" = 1 order by "caseId" '.format(
            _tblName
        )
        print("sql:",sql)
        return self._pgConn.exec_fetchall(sql)



    def case_delete_sql(self, ids) -> bool:
        # 逻辑删除状态置为 0

        sql = 'update {} set "dataValid" = 0  where "caseId" = \'{}\''.format(
            _tblName, ids
        )
        return self._pgConn.exec(sql)

    def get_online_device(self, state=None):
        sql = """
        SELECT a."caseId",a."caseName",a."address",a."coverImgUrl",a."location",a."AIfacilitator",
        count(b."deviceId") AS online_sum from tbl_case AS a LEFT JOIN tbl_device AS b ON
         b."caseId"=a."caseId" AND b."AIstatus"='true' WHERE a."AIfacilitator"='bjy'  group by a."caseId";
        """
        detail_sql = """
        SELECT a."caseId",a."caseName",a."address",a."coverImgUrl",a."location",a."AIfacilitator",
        b."deviceId",b."deviceName",b."AIstatus" AS device_state,b."createTime",b."updateTime" 
        from tbl_case AS a LEFT JOIN tbl_device AS b ON
         b."caseId"=a."caseId"  WHERE a."AIfacilitator"='bjy' and b."states"='1' and b."AIstatus"='{}';
        """.format(state) if state else ""
        bj_data = self._pgConn.exec_fetchall(detail_sql)
        boguan_sql = """
        SELECT a."caseId",a."caseName",a."address",a."coverImgUrl",a."location",
        count(b."deviceId") AS online_sum from tbl_case AS a LEFT JOIN tbl_device AS b ON
         b."caseId"=a."caseId" AND b."states"='1' and a."states"='1' group by a."caseId";
        """
        flag = "1" if state else "0"
        detail_boguan_sql = """
        SELECT a."caseId",a."caseName",a."address",a."coverImgUrl",a."location",
        b."deviceId",b."deviceName",b."states" AS device_state ,b."createTime",b."updateTime"
        from tbl_case AS a LEFT JOIN tbl_device AS b ON
         b."caseId"=a."caseId" AND a."states"='1' AND b."states"='{}' WHERE b."deviceId" IS NOT NULL ;
        """.format(flag) if flag else ""
        boguan_data = pgconn.boguan_db.exec_fetchall(detail_boguan_sql)

        return bj_data+boguan_data

    def get_cases_status(self):
        total_sql = "select COUNT(*) as total  from tbl_case where \"dataValid\" = 1;"
        total = self._pgConn.exec_fetchall(total_sql)[0]['total']
        detail_sql = """
                SELECT a."caseId",a."caseName"
                from tbl_case AS a LEFT JOIN tbl_device AS b on b."caseId"=a."caseId"  
                WHERE a."AIfacilitator"='bjy' and a."dataValid"=1 and  b."AIstatus"='true' GROUP BY a."caseId";
                """
        bj_data = self._pgConn.exec_fetchall(detail_sql)
        bj_num = len(bj_data)
        detail_boguan_sql = """
                SELECT a."caseId",a."caseName"
                from tbl_case AS a LEFT JOIN tbl_device AS b ON
                b."caseId"=a."caseId" AND a."states"='1' and a."dataValid"=1 AND b."states"='1' 
                WHERE b."deviceId" IS NOT NULL  GROUP BY a."caseId";
                """
        boguan_data = pgconn.boguan_db.exec_fetchall(detail_boguan_sql)
        boguan_num = len(boguan_data)
        return (total,bj_num+boguan_num,total-bj_num-boguan_num)

    def getaddress(self) -> list:
        sql = 'SELECT "caseId","address","location" FROM "public"."{}" where "dataValid" =1'.format(
            _tblName)
        return self._pgConn.exec_fetchall(sql)

    def get_playground(self, caseId=None) -> list:
        tmp = f' where a."case_id"={caseId} ' if caseId else ''
        sql = f'select b."AIfacilitator",a.*,b."caseName" from playground AS a left JOIN tbl_case AS b on a."case_id"=b."caseId" {tmp} order by b."caseName";'
        return self._pgConn.exec_fetchall(sql)

    def create_playground(self, dic):
        sql = 'insert into '
        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

        sql = f"""insert into playground ({sql_key}) values ({sql_val[:-1]}) RETURNING "{"id"}" """
        return pgconn.pgMainConn.exec_fetchone(sql)

    def update_playground(self, dic, keys, ids) -> bool:
        '''modify'''
        dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'

        sql = "update {} set {} where  ".format('playground', sql_key[:-1]) + " \"{}\" = '{}' ".format(keys, ids)
        return self._pgConn.exec(sql)

    def delete_playground(self,ids):
        sql = "delete from {} where \"id\" = '{}' ".format('playground', ids)
        return self._pgConn.exec(sql)









